package com.zheng.shop.admin.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.zheng.common.base.BaseController;
import com.zheng.common.base.BaseResult;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.shop.common.constant.ShopResult;
import com.zheng.shop.common.constant.ShopResultConstant;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.model.ShopBrand;
import com.zheng.shop.dao.model.ShopCategory;
import com.zheng.shop.rpc.api.ShopBrandService;
import com.zheng.shop.rpc.api.ShopCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/8
 * Time: 10:30
 */
@Controller
@Api(value = "品牌管理", description = "品牌管理")
@RequestMapping("/manage/product/brand")
public class BrandController extends BaseController {
    @Autowired
    private ShopBrandService brandService;
    @Autowired
    private ShopCategoryService categoryService;

    @ApiOperation(value = "品牌首页")
    @RequiresPermissions("product:brand:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/product/brand/index.jsp";
    }

    @ApiOperation(value = "获取所有品牌")
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Object list() {
        List<ShopBrand> brandList = brandService.selectList(null);
        return new ShopResult(ShopResultConstant.SUCCESS, brandList);
    }

    @ApiOperation(value = "品牌列表")
    @RequiresPermissions("product:brand:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, value = "sortName", defaultValue = "sort") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder) {
        Wrapper<ShopBrand> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        List<ShopBrand> rows = brandService.selectList(wrapper);
        int total = brandService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增品牌")
    @RequiresPermissions("product:brand:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/product/brand/create.jsp";
    }

    @ApiOperation(value = "新增品牌")
    @RequiresPermissions("product:brand:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody ShopBrand brand) {
        ComplexResult result = FluentValidator.checkAll()
                .on(brand.getName(), new LengthValidator(1, 20, "品牌名称"))
                .on(brand.getSort(), new NotNullValidator("品牌排序"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        //判断命名是否重复
        EntityWrapper<ShopBrand> brandEntityWrapper = new EntityWrapper<>();
        String name = brand.getName();
        name = StringUtils.deleteWhitespace(name);
        brandEntityWrapper.where("name='" + name + "'");
        if (brandService.selectCount(brandEntityWrapper) > 0) {
            return new ShopResult(ShopResultConstant.FAILED, "该品牌已存在，请更换名称！");

        }
        brand.setName(name);
        brand.setCtime(new Date());
        if (!brandService.insert(brand)) {
            return new ShopResult(ShopResultConstant.FAILED, "添加失败！");
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
    }

    @ApiOperation(value = "修改品牌")
    @RequiresPermissions("product:brand:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(Model model, @PathVariable("id") Integer id) {
        ShopBrand brand = brandService.selectById(id);
        model.addAttribute("brand", brand);
        return "/manage/product/brand/update.jsp";
    }

    @ApiOperation(value = "修改品牌")
    @RequiresPermissions("product:brand:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody ShopBrand brand) {
        ComplexResult result = FluentValidator.checkAll()
                .on(brand.getName(), new LengthValidator(1, 20, "品牌名称"))
                .on(brand.getSort(), new NotNullValidator("品牌排序"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        //判断命名是否重复
        EntityWrapper<ShopBrand> brandEntityWrapper = new EntityWrapper<>();
        String name = brand.getName();
        name = StringUtils.deleteWhitespace(name);
        brandEntityWrapper.where("name='" + name + "'");
        ShopBrand oldBrand = brandService.selectOne(brandEntityWrapper);
        if (null != oldBrand && !oldBrand.getId().equals(brand.getId())) {
            return new ShopResult(ShopResultConstant.FAILED, "该品牌已存在，请更换名称！");
        }
        brand.setName(name);
        brand.setMtime(new Date());
        if (!brandService.updateById(brand)) {
            return new ShopResult(ShopResultConstant.FAILED, "修改品牌失败");
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "删除品牌")
    @RequiresPermissions("product:brand:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestBody List<Integer> ids) {
        try {
            brandService.deleteBrand(ids);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "品牌排序")
    @RequestMapping(value = "/sort", method = RequestMethod.POST)
    @ResponseBody
    public Object sort(@RequestBody List<ShopBrand> brandList) {
        try {
            brandService.updateSort(brandList);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "品牌分类")
    @RequiresPermissions("product:brand:category")
    @RequestMapping(value = "/category/{id}", method = RequestMethod.GET)
    public String category(Model model, @PathVariable("id") Integer id) {
        List<ShopCategory> categoryList = categoryService.selectList(null);
        model.addAttribute("productCategoryList", categoryList);

        List<Map<String, Object>> selectedList = brandService.selectBrandCategoryMap(id);
        model.addAttribute("selectedList", selectedList);

        ShopBrand brand = brandService.selectById(id);
        model.addAttribute("brand", brand);
        return "/manage/product/brand/brandCategory.jsp";
    }

    @ApiOperation(value = "品牌分类")
    @RequestMapping(value = "/category", method = RequestMethod.POST)
    @RequiresPermissions("product:brand:category")
    @ResponseBody
    public Object category(@RequestBody JSONObject params) {
        Integer brandId = params.getInteger("brandId");
        Object obj = params.get("ids");
        List<Integer> brandCategoryIds = (List<Integer>) obj;
        try {
            brandService.updateBrandCategory(brandId, brandCategoryIds);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }
}
